package com.thh.shirodemo.controller;

import com.thh.shirodemo.bean.Goods;
import com.thh.shirodemo.bean.User;
import com.thh.shirodemo.mapper.GoodsMapper;
import com.thh.shirodemo.service.SeckillService;
import com.thh.shirodemo.util.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;


/**
 * @author shkstart
 * @create 2022-07-27-0:13
 */
@Controller
@RequiresPermissions("salary")
public class SckillController {
    @Autowired
    SeckillService seckillService;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    RedisUtil redisUtil;
    @RequestMapping("/doSeckill")
    public String Sckill(){
        return "SeckillActivity";
    }

    /**
     * 执行秒杀活动
     * @return
     */
    @ResponseBody
    @RequestMapping("/doSeckillNow")
    public String sckillNow(){
        //获取当前对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getSession().getAttribute("currentUser");
        String secKillMsg = seckillService.doSecKill(currentUser.getUserId(),currentUser.getUserName(),goodsMapper.getSecKillGood());
        return secKillMsg;
    }

    /**
     * 显示正在参与的秒杀商品以及活动
     */
    @RequestMapping("/getSecKill")
    public String getSecKill(Model model){
        HashMap<String, Object> map = new HashMap<>();
        String goodName = goodsMapper.getSecKillGood();
        if(goodName!=null){
            Goods good = goodsMapper.getGoodsByName(goodName);
            map.put("goodName",good.getGoodsName());
            map.put("goodId",good.getGoodsId());
            map.put("goodPrice",good.getGoodsPrice());
            String kcKey="sk:"+good.getGoodsName()+"count";
            map.put("goodStock",(Integer)redisUtil.get(kcKey));
            map.put("msg","以上是这次开启的秒杀活动:");
        }else{
            map.put("goodName",null);
            map.put("goodId",null);
            map.put("goodPrice",null);
            map.put("goodStock",null);
            map.put("msg","暂时还没有秒杀活动哦~敬请关注");
        }
        model.addAttribute("currentSecKill",map);
        return "CurrentSecKill";
    }
}
